import { useEffect, useRef, useState } from 'react';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface MilkdownPreviewProps {
  content: string;
  isDark?: boolean;
  className?: string;
  selectedFont?: string;
  'data-preview'?: string;
}

// 字体选项
export const fontOptions = [
  { value: 'default', label: '默认字体', font: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
  { value: 'serif', label: '衬线字体', font: 'Georgia, "Times New Roman", serif' },
  { value: 'sans', label: '无衬线字体', font: 'Arial, Helvetica, sans-serif' },
  { value: 'mono', label: '等宽字体', font: 'Consolas, Monaco, "Courier New", monospace' },
  { value: 'elegant', label: '优雅字体', font: '"Palatino Linotype", "Book Antiqua", Palatino, serif' },
  { value: 'modern', label: '现代字体', font: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif' },
  { value: 'chinese', label: '中文字体', font: '"Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif' },
  { value: 'yahei', label: '微软雅黑', font: '"Microsoft YaHei", "Microsoft JhengHei", "PingFang SC", "Hiragino Sans GB", sans-serif' },
  { value: 'simhei', label: '黑体', font: '"SimHei", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", sans-serif' },
  { value: 'simsun', label: '宋体', font: '"SimSun", "NSimSun", "FangSong", "KaiTi", serif' }
];

export function MilkdownPreview({ content, isDark = false, className, selectedFont = 'default', 'data-preview': dataPreview }: MilkdownPreviewProps) {
  const previewRef = useRef<HTMLDivElement>(null);

  // 动态加载highlight.js样式
  useEffect(() => {
    const loadHighlightStyle = async () => {
      if (isDark) {
        await import('highlight.js/styles/github-dark.css');
      } else {
        await import('highlight.js/styles/github.css');
      }
    };
    loadHighlightStyle();
  }, [isDark]);

  // 复制代码到剪贴板
  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success('代码已复制到剪贴板', {
        style: {
          color: '#10b981'
        }
      });
    } catch (err) {
      console.error('复制失败:', err);
      toast.error('复制失败，请手动复制');
    }
  };

  // 获取当前选中的字体
  const getCurrentFont = () => {
    const fontOption = fontOptions.find(option => option.value === selectedFont);
    return fontOption ? fontOption.font : fontOptions[0].font;
  };

  useEffect(() => {
    if (previewRef.current) {
      // 使用markdown-it渲染内容，启用语法高亮
      const md = new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        breaks: true,
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return hljs.highlight(str, { language: lang }).value;
            } catch (__) {}
          }
          return ''; // 使用默认的转义
        }
      });
      
      const html = md.render(content || '请编辑文档内容');
      previewRef.current.innerHTML = html;

      // 美化代码块
      const codeBlocks = previewRef.current.querySelectorAll('pre code');
      codeBlocks.forEach((codeBlock) => {
        const pre = codeBlock.parentElement;
        if (pre) {
          // 获取语言标识
          const language = codeBlock.className.replace('language-', '') || 'text';
          const codeText = codeBlock.textContent || '';

          // 创建美化后的代码块容器
          const enhancedCodeBlock = document.createElement('div');
          enhancedCodeBlock.className = cn(
            'relative rounded-2xl overflow-hidden my-8 shadow-2xl',
            isDark 
              ? 'bg-gray-900/95 backdrop-blur-sm' 
              : 'bg-white/95 backdrop-blur-sm'
          );

          // 创建顶部装饰条
          const topBar = document.createElement('div');
          topBar.className = cn(
            'h-1 w-full',
            isDark 
              ? 'bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500' 
              : 'bg-gradient-to-r from-blue-400 via-purple-400 to-pink-400'
          );

          // 创建头部栏
          const header = document.createElement('div');
          header.className = cn(
            'flex items-center justify-between px-6 py-1 border-b',
            isDark 
              ? 'bg-gradient-to-r from-gray-800 to-gray-700 border-gray-600/30' 
              : 'bg-gradient-to-r from-gray-50 to-gray-100 border-gray-200/30'
          );

          // 语言标识
          const languageBadge = document.createElement('span');
          languageBadge.className = cn(
            'text-xs font-mono px-4 py-1.5 rounded-full font-semibold tracking-wide',
            isDark 
              ? 'bg-gray-700 text-gray-300 shadow-lg' 
              : 'bg-gray-200 text-gray-700 shadow-md'
          );
          languageBadge.textContent = language;

          // 复制按钮
          const copyButton = document.createElement('button');
          copyButton.className = cn(
            'flex items-center space-x-2 px-4 py-1.5 rounded-lg text-xs font-medium transition-all duration-300 hover:scale-105',
            isDark 
              ? 'text-gray-400 hover:text-white hover:bg-gray-700 shadow-lg' 
              : 'text-gray-500 hover:text-gray-700 hover:bg-gray-200 shadow-md'
          );
          copyButton.innerHTML = `
            <i class="fa-solid fa-copy"></i>
            <span>复制</span>
          `;
          copyButton.onclick = () => copyToClipboard(codeText);

          header.appendChild(languageBadge);
          header.appendChild(copyButton);

          // 创建代码容器，保持原始代码块结构以维持语法高亮
          const codeContainer = document.createElement('div');
          codeContainer.className = cn(
            'overflow-x-auto -mt-1',
            isDark ? 'bg-gray-900' : 'bg-gray-50'
          );

          // 保持原始的pre和code结构，只添加样式
          const newPre = document.createElement('pre');
          newPre.className = 'm-0 p-6';
          
          const newCode = document.createElement('code');
          newCode.className = codeBlock.className; // 保持原始类名以维持语法高亮
          newCode.innerHTML = codeBlock.innerHTML; // 保持原始HTML以维持语法高亮
          
          // 优化代码文字颜色
          newCode.style.color = '#ffffff';
          newCode.style.fontSize = '14px';
          newCode.style.lineHeight = '1.6';
          newCode.style.fontFamily = getCurrentFont();
          
          // 强制覆盖语法高亮的颜色
          const codeElements = newCode.querySelectorAll('*');
          codeElements.forEach((element) => {
            if (element instanceof HTMLElement) {
              element.style.color = '#ffffff';
            }
          });
          
          newPre.appendChild(newCode);
          codeContainer.appendChild(newPre);
          
          enhancedCodeBlock.appendChild(topBar);
          enhancedCodeBlock.appendChild(header);
          enhancedCodeBlock.appendChild(codeContainer);

          // 替换原始代码块
          pre.parentNode?.replaceChild(enhancedCodeBlock, pre);
        }
      });

      // 美化行内代码
      const inlineCodes = previewRef.current.querySelectorAll('code:not(pre code)');
      inlineCodes.forEach((code) => {
        code.className = cn(
          'px-2.5 py-1 rounded-lg text-sm font-mono font-medium shadow-sm',
          isDark 
            ? 'bg-gray-800/80 text-gray-100 border border-gray-700/50' 
            : 'bg-gray-100/80 text-gray-800 border border-gray-200/50'
        );
      });

      // 美化表格
      const tables = previewRef.current.querySelectorAll('table');
      tables.forEach((table) => {
        table.className = cn(
          'w-full border-collapse rounded-2xl overflow-hidden shadow-2xl my-8 border',
          isDark ? 'bg-gray-800/95 border-gray-700/50' : 'bg-white/95 border-gray-200/50'
        );
        
        // 美化表头
        const thead = table.querySelector('thead');
        if (thead) {
          thead.className = cn(
            isDark ? 'bg-blue-600' : 'bg-blue-500'
          );
          // 强制设置背景色
          thead.style.backgroundColor = isDark ? '#2563eb' : '#3b82f6';
          
          const headerCells = thead.querySelectorAll('th');
          headerCells.forEach((th) => {
            th.className = cn(
              'px-6 py-4 text-left font-bold text-sm tracking-wide',
              isDark 
                ? 'text-white border-b border-blue-500' 
                : 'text-white border-b border-blue-400'
            );
            // 强制设置文字颜色
            th.style.color = '#ffffff';
            th.style.backgroundColor = isDark ? '#2563eb' : '#3b82f6';
          });
        }
        
        // 美化表格行
        const tbody = table.querySelector('tbody');
        if (tbody) {
          const rows = tbody.querySelectorAll('tr');
          rows.forEach((row, index) => {
            row.className = cn(
              'transition-all duration-300 ease-out hover:scale-[1.01]',
              isDark 
                ? 'bg-gray-800/80 hover:bg-gray-700/90 hover:shadow-inner' 
                : 'bg-white/80 hover:bg-gray-50/90 hover:shadow-inner'
            );
            
            const cells = row.querySelectorAll('td');
            cells.forEach((td) => {
              td.className = cn(
                'px-6 py-4 text-sm border-b transition-all duration-200',
                isDark 
                  ? 'text-gray-300 border-gray-700/50' 
                  : 'text-gray-700 border-gray-200/50'
              );
            });
          });
        }
      });

      // 美化标题
      const headings = previewRef.current.querySelectorAll('h1, h2, h3, h4, h5, h6');
      headings.forEach((heading) => {
        const level = parseInt(heading.tagName.charAt(1));
        const baseClasses = 'font-bold tracking-tight';
        
        switch (level) {
          case 1:
            heading.className = cn(
              baseClasses, 'text-4xl mb-8 mt-12 pb-3',
              isDark 
                ? 'text-gray-100 border-b-2 border-gray-700 bg-gradient-to-r from-gray-900 to-gray-800 p-4 rounded-xl' 
                : 'text-gray-900 border-b-2 border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100 p-4 rounded-xl'
            );
            break;
          case 2:
            heading.className = cn(
              baseClasses, 'text-3xl mb-6 mt-10 pb-2',
              isDark 
                ? 'text-gray-100 border-b border-gray-700' 
                : 'text-gray-900 border-b border-gray-200'
            );
            break;
          case 3:
            heading.className = cn(
              baseClasses, 'text-2xl mb-4 mt-8',
              isDark ? 'text-gray-200' : 'text-gray-800'
            );
            break;
          case 4:
            heading.className = cn(
              baseClasses, 'text-xl mb-3 mt-6',
              isDark ? 'text-gray-200' : 'text-gray-800'
            );
            break;
          case 5:
            heading.className = cn(
              baseClasses, 'text-lg mb-2 mt-4',
              isDark ? 'text-gray-300' : 'text-gray-700'
            );
            break;
          case 6:
            heading.className = cn(
              baseClasses, 'text-base mb-1 mt-3',
              isDark ? 'text-gray-400' : 'text-gray-600'
            );
            break;
        }
      });

      // 美化列表
      const lists = previewRef.current.querySelectorAll('ul, ol');
      lists.forEach((list) => {
        list.className = cn(
          'my-6 space-y-3 pl-6',
          isDark ? 'text-gray-300' : 'text-gray-700'
        );
        
        const listItems = list.querySelectorAll('li');
        listItems.forEach((li) => {
          li.className = cn(
            'leading-relaxed relative',
            isDark ? 'text-gray-300' : 'text-gray-700'
          );
        });
      });

      // 美化引用块
      const blockquotes = previewRef.current.querySelectorAll('blockquote');
      blockquotes.forEach((blockquote) => {
        blockquote.className = cn(
          'border-l-4 pl-6 py-4 my-6 italic rounded-r-xl shadow-lg',
          isDark 
            ? 'border-blue-500 bg-gradient-to-r from-gray-800/50 to-gray-700/30 text-gray-300' 
            : 'border-blue-400 bg-gradient-to-r from-blue-50/50 to-gray-50/30 text-gray-700'
        );
      });

      // 美化水平分割线
      const horizontalRules = previewRef.current.querySelectorAll('hr');
      horizontalRules.forEach((hr) => {
        hr.className = cn(
          'my-12 border-0 h-1 rounded-full',
          isDark ? 'bg-gradient-to-r from-gray-700 via-gray-600 to-gray-700' : 'bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200'
        );
      });

      // 美化链接
      const links = previewRef.current.querySelectorAll('a');
      links.forEach((link) => {
        link.className = cn(
          'font-medium transition-all duration-300 hover:scale-105',
          isDark 
            ? 'text-blue-400 hover:text-blue-300 underline decoration-blue-500/50 hover:decoration-blue-400' 
            : 'text-blue-600 hover:text-blue-500 underline decoration-blue-400/50 hover:decoration-blue-500'
        );
      });

      // 美化强调文本
      const strongElements = previewRef.current.querySelectorAll('strong');
      strongElements.forEach((strong) => {
        strong.className = cn(
          'font-bold',
          isDark ? 'text-gray-200' : 'text-gray-900'
        );
      });

      const emElements = previewRef.current.querySelectorAll('em');
      emElements.forEach((em) => {
        em.className = cn(
          'italic',
          isDark ? 'text-gray-300' : 'text-gray-700'
        );
      });

      // 美化删除线
      const delElements = previewRef.current.querySelectorAll('del');
      delElements.forEach((del) => {
        del.className = cn(
          'line-through opacity-60',
          isDark ? 'text-gray-500' : 'text-gray-500'
        );
      });

      // 美化段落
      const paragraphs = previewRef.current.querySelectorAll('p');
      paragraphs.forEach((p) => {
        p.className = cn(
          'leading-relaxed mb-6 text-lg',
          isDark ? 'text-gray-300' : 'text-gray-700'
        );
        p.style.fontFamily = getCurrentFont();
      });

      // 美化图片
      const images = previewRef.current.querySelectorAll('img');
      images.forEach((img) => {
        img.className = cn(
          'max-w-full h-auto rounded-2xl shadow-2xl my-8 transition-all duration-300 hover:scale-105',
          isDark ? 'border border-gray-700/50' : 'border border-gray-200/50'
        );
      });

      // 应用字体到所有文本元素
      const allTextElements = previewRef.current.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote, a, strong, em, del, span, div');
      allTextElements.forEach((element) => {
        if (element instanceof HTMLElement) {
          element.style.fontFamily = getCurrentFont();
        }
      });
    }
  }, [content, isDark, selectedFont]);

  return (
    <div 
      ref={previewRef}
      className={cn(
        'milkdown-preview prose prose-lg max-w-none p-6 leading-relaxed h-full overflow-y-auto',
        isDark ? 'dark prose-invert' : 'light',
        'bg-gradient-to-br from-transparent to-transparent',
        className
      )}
      style={{ fontFamily: getCurrentFont() }}
      data-preview={dataPreview}
    />
  );
} 